package lvbu.wang.lvbuoperator;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.qing.library.services.ListenerNetStateService;
import com.qing.library.utils.IntentUtils;
import com.qing.library.widget.CustomProgress;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;

import lvbu.wang.lvbuoperator.bean.JsonApp;
import lvbu.wang.lvbuoperator.bean.JsonManager;
import lvbu.wang.lvbuoperator.bean.MotorInfo;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.App;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.engine.BleServerConfig;
import lvbu.wang.lvbuoperator.engine.IotServerConfig;
import lvbu.wang.lvbuoperator.function.nologin.NoLoginOperationEntryActivity;
import lvbu.wang.lvbuoperator.http.IotHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.ui.ProductSelectActivity;

/**
 * Created by DaiQing.Zha on 2016/9/14 0014.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";

    private EditText mEtNickName;   //昵称
    private EditText mEtPwd;    //密码
    private Button mBtnLogin;   //登录
    private TextView mTvAppVersion;   //app版本
    private CustomProgress mCustomProgress;  //自定义进度条
    private RadioGroup mRgMotorType, mRgAppVersion;    //电机类型[物联网版，蓝牙版];app版本[生产版，测试版]
    private RadioButton mRbLvBuIotOperation, mRbLvBuBleOperation;   //物联网版；蓝牙版
    private RadioButton mRbAppVersionSC, mRbAppVersionCS;   //生产版；生产版
    private String mDirName = "version";    //文件路径
    private String mFileName = "install.apk";   //文件名称

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        versionUpgrade();
        startService(new Intent(this, BluetoothLEService.class));
        startService(new Intent(this, ListenerNetStateService.class));

    }

    @Override
    protected void init() {
        mEtNickName = findView(R.id.et_nickName);
        mEtPwd = findView(R.id.et_pwd);
        mBtnLogin = findView(R.id.btn_login);
        mTvAppVersion = findView(R.id.tv_appVersion);

        mRgMotorType = findView(R.id.rgMotorType);
        mRbLvBuIotOperation = findView(R.id.rbLvBuIotOperation);
        mRbLvBuBleOperation = findView(R.id.rbLvBuBleOperation);
        mRgAppVersion = findView(R.id.rgAppVersion);
        mRbAppVersionSC = findView(R.id.rbAppVersionSC);
        mRbAppVersionCS = findView(R.id.rbAppVersionCS);


        mCustomProgress = new CustomProgress(this);
        mEtNickName.setText(getNickname());
        Log.e(TAG, "init: " + getPwd(), null);
        mEtPwd.setText(getPwd());
        mBtnLogin.setOnClickListener(this);
        getSupportActionBar().setTitle(getString(R.string.xml_login_login));

        ConstantsValue.MOTOR_TYPE = BaseActivity.getMotorType(LoginActivity.this);
        if (ConstantsValue.MOTOR_TYPE == ConstantsValue.MOTOR_TYPE_IOT_OPERATION)
            mRbLvBuIotOperation.setChecked(true);
        if (ConstantsValue.MOTOR_TYPE == ConstantsValue.MOTOR_TYPE_BLE_OPERATION)
            mRbLvBuBleOperation.setChecked(true);
        ConstantsValue.APP_VERSION = BaseActivity.getAppVersion(LoginActivity.this);
        if (ConstantsValue.APP_VERSION == ConstantsValue.APP_VERSION_SC)
            mRbAppVersionSC.setChecked(true);
        if (ConstantsValue.APP_VERSION == ConstantsValue.APP_VERSION_CS)
            mRbAppVersionCS.setChecked(true);

        mRgMotorType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rbLvBuIotOperation) {
                    ConstantsValue.MOTOR_TYPE = ConstantsValue.MOTOR_TYPE_IOT_OPERATION;
                }
                if (checkedId == R.id.rbLvBuBleOperation) {
                    ConstantsValue.MOTOR_TYPE = ConstantsValue.MOTOR_TYPE_BLE_OPERATION;
                }
                BaseActivity.setMotorType(LoginActivity.this, ConstantsValue.MOTOR_TYPE);
            }
        });
        mRgAppVersion.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rbAppVersionSC) {  //生产
                    ConstantsValue.APP_VERSION = ConstantsValue.APP_VERSION_SC;
                    IotServerConfig.USE_SERVER_MODE = IotServerConfig.Mode.RELEASE; //物联网版
                    BleServerConfig.USE_SERVER_MODE = BleServerConfig.Mode.RELEASE; //蓝牙版
                }
                if (checkedId == R.id.rbAppVersionCS) {  //测试
                    ConstantsValue.APP_VERSION = ConstantsValue.APP_VERSION_CS;
                    IotServerConfig.USE_SERVER_MODE = IotServerConfig.Mode.DEBUG;   //物联网版
                    BleServerConfig.USE_SERVER_MODE = BleServerConfig.Mode.DEBUG;   //蓝牙版

                }
                BaseActivity.setAppVersion(LoginActivity.this, ConstantsValue.APP_VERSION);
            }
        });
        mTvAppVersion.setText("当前版本：" + getVersionName(this));

        // 蓝牙搜索6.0以上需要的权限
        AndPermission.with(this).runtime().permission(Permission.ACCESS_COARSE_LOCATION)
                .onDenied(data -> showToastMsg("权限获取失败，请手动开启权限")).start();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.btn_login:
                login();//登录
                break;

        }
    }

    /**
     * 版本升级
     */
    private void versionUpgrade() {
        try {
            Executors.newCachedThreadPool().execute(() -> {
                final JsonApp.AppVersion newVersion = getNewVersion();
                if (newVersion.getVerCode() > getCurrentVersionCode()) { // 有新版本
                    Log.e("TAG", "有新的版本了");
                    String versionName = getCurrentVersionName();
                    String versionNameNew = newVersion.getVerName();
                    final String message = "当前版本:" + versionName + "，发现新版本:" + versionNameNew + "，开始更新！";
                    showToastMsg(message);
                    runOnUiThread(() -> {
                        final ProgressDialog pDialog = new ProgressDialog(getContext());
                        pDialog.setCancelable(false);
                        pDialog.setCanceledOnTouchOutside(false);
                        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        pDialog.setIndeterminate(false);// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
                        pDialog.setTitle("正在下载新版本");
                        pDialog.setMessage("请稍候...");
                        pDialog.show();

                        // 开始下载安装 begin///////////////////////////////////////////////////////////////
                        new Thread() {
                            public void run() {
                                HttpClient client = new DefaultHttpClient();
                                String address = IotHttpHelp.getUrlAssignApp(newVersion.getId());
                                HttpGet get = new HttpGet(address);
                                HttpResponse response;
                                try {
                                    response = client.execute(get);
                                    HttpEntity entity = response.getEntity();
                                    long length = entity.getContentLength();
                                    pDialog.setMax((int) length);
                                    InputStream is = entity.getContent();
                                    FileOutputStream fileOutputStream = null;
                                    if (is != null) {
                                        File file = null;
                                        if (BaseActivity.hasSDCardMounted()) {
                                            file = new File(getExternalFilesDir(mDirName), mFileName);// SDCard/Android/data/应用的包名/files/目录
                                        } else {
                                            File dir = getDir(mDirName, Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);// data/data/包名/mDirName/
                                            file = new File(dir, mFileName);
                                            String[] command = {"chmod", "777", dir.getPath() + "/" + mFileName};
                                            ProcessBuilder builder = new ProcessBuilder(command);
                                            try {
                                                builder.start();
                                            } catch (Exception e) {
                                            }
                                        }
                                        fileOutputStream = new FileOutputStream(file);
                                        byte[] buf = new byte[1024];
                                        int ch = -1;
                                        int count = 0;
                                        while ((ch = is.read(buf)) != -1) {
                                            fileOutputStream.write(buf, 0, ch);
                                            count += ch;
                                            if (length > 0) {
                                                pDialog.setProgress(count);
                                            }
                                        }
                                    }
                                    fileOutputStream.flush();
                                    if (fileOutputStream != null) {
                                        fileOutputStream.close();
                                    }
                                    Intent intent1;
//                                        Intent intent = new Intent(Intent.ACTION_VIEW);
                                    if (BaseActivity.hasSDCardMounted()) {
//                                            intent.setDataAndType(
//                                                    Uri.fromFile(new File(getExternalFilesDir(mDirName), mFileName)), "application/vnd.android.package-archive"); //设置文件类型为.apk，下载完成后，系统会自动检测安装
                                        intent1 = Quick.getInstallAppIntent(new File(getExternalFilesDir(mDirName), mFileName), App.getInstance().getPackageName() + ".fileprovider", false);
                                    } else {
//                                            intent.setDataAndType(Uri.fromFile(new File(getDir(mDirName
//                                                    , Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE)
//                                                    , mFileName)), "application/vnd.android.package-archive");  //设置文件类型为.apk，下载完成后，系统会自动检测安装
                                        intent1 = Quick.getInstallAppIntent(new File(getDir(mDirName
                                                , Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE)
                                                , mFileName), App.getInstance().getPackageName() + ".fileprovider", false);
                                    }
                                    startActivity(intent1);
                                    Log.e("TAG", intent1 + "---------------");
                                    pDialog.cancel();
                                } catch (Exception e) {
                                    Log.e("TAG", e.getMessage() + "--------");
                                }
                            }
                        }.start();

                    });
                }
                runOnUiThread(() -> mBtnLogin.setVisibility(View.VISIBLE));
            });
        } catch (Exception e) {
            Log.e("TAG", e.getMessage());
        }
    }

    /**
     * 获取当前版本号
     *
     * @return
     */
    private int getCurrentVersionCode() {
        int verCode = -1;
        try {
            verCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return verCode;
    }

    /**
     * 获取当前版本名
     *
     * @return
     */
    private String getCurrentVersionName() {
        String verName = "";
        try {
            verName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return verName;
    }

    /**
     * 获取最新版本号
     *
     * @return
     */
    private JsonApp.AppVersion getNewVersion() {
        int verCode = getCurrentVersionCode();
        Map<String, Object> queryStrings = new HashMap<String, Object>();
        queryStrings.put("device", "android");
        queryStrings.put("kind", "吕布操作员");
        queryStrings.put("verCodeCurrent", verCode);
        String source = IotHttpHelp.getData(RouteConstant.Get_JsonApp_AppVersion_New, queryStrings, true, getContext());
        if (IotHttpHelp.checkSource(source)) {
            return new Gson().fromJson(source, JsonApp.AppVersion.class);
        }
        return new JsonApp.AppVersion();
    }

    /**
     * 登录
     */
    private void login() {
        final String nickname = mEtNickName.getText().toString().trim();
        final String password = mEtPwd.getText().toString();
        mBtnLogin.setEnabled(false);
        mCustomProgress.show(this, getString(R.string.xml_login_loginIng), false, null);
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> queryStrings = new HashMap<>();
                queryStrings.put("nickname", nickname);
                queryStrings.put("password", password);
                queryStrings.put("characteristic", getCharacteristic());
                queryStrings.put("origin", getOrigin());
                String source = IotHttpHelp.getData(RouteConstant.GET_JSON_MANAGER_MANAGER_LOGIN_STATUS, queryStrings, false, LoginActivity.this);
                mCustomProgress.dissMiss();
                runOnUiThread(new Runnable() {
                    public void run() {
                        mBtnLogin.setEnabled(true);
                    }
                });
                if (!IotHttpHelp.checkSource(source)) {
                    showToastMsg(IotHttpHelp.source2Message(LoginActivity.this, source));
                    return;
                }
                JsonManager.ManagerLoginStatus managerLoginStatus = new Gson().fromJson(source, JsonManager.ManagerLoginStatus.class);
                if (managerLoginStatus.getLoginSuccess()) {
                    setToken(managerLoginStatus.getToken());
                    Log.e("mainHHH", "set token = " + managerLoginStatus.getToken());
                    setNickname(nickname);
                    setPwd(password);
                    setManagerId(managerLoginStatus.getManagerId());
//                    IntentUtils.startActivity(LoginActivity.this,IotIndexActivity.class);
                    IntentUtils.startActivity(LoginActivity.this, ProductSelectActivity.class);
                } else {
                    showToastMsg(managerLoginStatus.getErrorMessage()); //显示错误
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_index, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_quit) {    //退出登录
            setToken("");
            setNickname("");
            setPwd("");
            setManagerId(0);
            App.getInstance().setMotor(new MotorInfo());
            finish();
        }
        if (id == R.id.action_noLoginOperation) {
            startActivity(new Intent(this, NoLoginOperationEntryActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }
}
